package com.coffee.admin.service.platform.impl;

import com.coffee.admin.api.platform.query.PlatformRolePermissionQuery;
import com.coffee.admin.api.platform.query.PlatformRoleQuery;
import com.coffee.admin.api.platform.req.PlatformRoleReq;
import com.coffee.admin.api.platform.result.PlatformRoleResult;
import com.coffee.admin.api.platform.service.PlatformRoleService;
import com.coffee.admin.api.supplier.query.SupplierRolePermissionQuery;
import com.coffee.admin.service.platform.bean.Platform;
import com.coffee.admin.service.platform.bean.PlatformRole;
import com.coffee.admin.service.platform.bean.PlatformRolePermission;
import com.coffee.admin.service.platform.dao.PlatformRoleDao;
import com.coffee.admin.service.platform.dao.PlatformRolePermissionDao;
import com.coffee.admin.service.platform.dao.PlatformRoleRelationDao;
import com.coffee.admin.service.supplier.bean.SupplierRolePermission;
import com.coffee.core.entity.Page;
import com.coffee.core.entity.PagerInfo;
import com.coffee.core.enums.ExceptionEnum;
import com.coffee.core.exception.BusinessException;
import com.coffee.core.exception.ValidateBusinessException;
import com.coffee.core.util.BeanUtilExt;
import com.coffee.core.util.DTOUtils;
import com.coffee.core.util.StringUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboService;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;


@DubboService(dynamic = true)
public class PlatformRoleServiceImpl implements PlatformRoleService {
    @Resource
    private PlatformRoleDao platformRoleDao;
    @Resource
    private PlatformRoleRelationDao platformRoleRelationDao;
    @Resource
    private PlatformRolePermissionDao platformRolePermissionDao;

    @Override
    public Page<PlatformRoleResult> getPager(PlatformRoleQuery param, PagerInfo pr) {
        Page<PlatformRoleResult> pager = new Page<PlatformRoleResult>(pr.getStart(), pr.getPageSize());
        Integer count = platformRoleDao.count(param);
        pager.setTotalPage(count);
        if (count > 0) {
            List<PlatformRole> list = platformRoleDao.page(param, pr.getStart(), pr.getPageSize());
            List<PlatformRoleResult> platformRoleResults = DTOUtils.convertList(list, PlatformRoleResult.class);
            platformRoleResults.forEach(role -> {
                Integer amount = platformRoleRelationDao.countByPlatformRoleId(role.getId());
                role.setCount(amount);
                //获取权限
                PlatformRolePermissionQuery query = new PlatformRolePermissionQuery();
                query.setPlatformRoleId(role.getId());
                List<PlatformRolePermission> platformRolePermissions = platformRolePermissionDao.list(query);
                if (CollectionUtils.isNotEmpty(platformRolePermissions)) {
                    List<Integer> permissionList = platformRolePermissions.stream().map(rl -> rl.getPlatformPermissionId()).collect(Collectors.toList());
                    role.setPermissionIds(permissionList.toArray(new Integer[]{}));
                }
            });
            pager.setData(platformRoleResults);
        }
        return pager;
    }

    @Override
    public Integer count(PlatformRoleQuery param) {
        Integer count = platformRoleDao.count(param);
        return count;
    }

    @Override
    public PlatformRoleResult getDetail(Integer id) {
        PlatformRole item = platformRoleDao.findById(id);
        if (item == null) {
            return null;
        }
        PlatformRoleResult result = new PlatformRoleResult();
        BeanUtilExt.copyProperties(result, item);

        return result;
    }

    @Override
    public List<PlatformRoleResult> getList(PlatformRoleQuery param, PagerInfo pr) {
        List<PlatformRole> list = platformRoleDao.page(param, pr.getStart(), pr.getPageSize());
        return DTOUtils.convertList(list, PlatformRoleResult.class);
    }

    @Override
    public List<PlatformRoleResult> getList(PlatformRoleQuery param) {
        List<PlatformRole> list = platformRoleDao.page(param, 0, Integer.MAX_VALUE);
        return DTOUtils.convertList(list, PlatformRoleResult.class);
    }

    @Override
    public List<PlatformRoleResult> getList() {
        PlatformRoleQuery param = new PlatformRoleQuery();
        List<PlatformRole> list = platformRoleDao.page(param, 0, Integer.MAX_VALUE);
        return DTOUtils.convertList(list, PlatformRoleResult.class);
    }


    @Override
    public void delete(Integer id) throws BusinessException {
        ValidateBusinessException.assertIdNotNull(id, ExceptionEnum.ERROR_1309);
        PlatformRole platformRole = this.platformRoleDao.findById(id);
        ValidateBusinessException.assertNonNull(platformRole, ExceptionEnum.ERROR_1310);
        ValidateBusinessException.assertFalse("N".equalsIgnoreCase(platformRole.getCanDelete()), ExceptionEnum.ERROR_1311);
        platformRoleDao.deleteById(id);
    }

    @Override
    public void addOrUpdate(PlatformRoleReq result) throws BusinessException {
        String roleName = result.getName();
        ValidateBusinessException.assertStringNotBlank(roleName, ExceptionEnum.ERROR_1312);

        Integer[] permissionIds = result.getPermissionIds();
        ValidateBusinessException.assertTrue(result.getPermissionIds().length > 0, ExceptionEnum.ERROR_1313);

        Integer roleId = result.getId();
        if (roleId != null && roleId > 0) {
            PlatformRole platformRole = platformRoleDao.findById(roleId);
            ValidateBusinessException.assertTrue("Y".equals(platformRole.getCanDelete()), ExceptionEnum.ERROR_1314);
            platformRole.setName(roleName);
            platformRoleDao.updateById(platformRole);
            batchUpdateRolePermission(platformRole.getId(), new ArrayList<>(Arrays.asList(permissionIds)));
        } else {
            PlatformRole role = new PlatformRole();
            role.setCreateTime(new Date());
            role.setCanDelete("Y");
            role.setName(result.getName());
            platformRoleDao.insert(role);
            batchUpdateRolePermission(role.getId(), new ArrayList<>(Arrays.asList(permissionIds)));
        }
    }

    @Override
    public Map<Integer, PlatformRoleResult> getItemMap(Set<Integer> idSet) {
        Map<Integer, PlatformRoleResult> map = new HashMap<Integer, PlatformRoleResult>();
        List<PlatformRole> list = platformRoleDao.findByIds(StringUtil.setToList(idSet));
        List<PlatformRoleResult> resultList = DTOUtils.convertList(list, PlatformRoleResult.class);
        for (PlatformRoleResult item : resultList) {
            map.put(item.getId(), item);
        }
        return map;
    }

    @Override
    public Map<Integer, PlatformRoleResult> getItemMap() {
        Map<Integer, PlatformRoleResult> map = new HashMap<Integer, PlatformRoleResult>();
        PlatformRoleQuery param = new PlatformRoleQuery();
        List<PlatformRole> list = platformRoleDao.page(param, 0, Integer.MAX_VALUE);
        List<PlatformRoleResult> resultList = DTOUtils.convertList(list, PlatformRoleResult.class);
        for (PlatformRoleResult item : resultList) {
            map.put(item.getId(), item);
        }
        return map;
    }


    public void batchUpdateRolePermission(Integer roleId, List<Integer> permissionIdList) {
        platformRolePermissionDao.deleteByPlatformRoleId(roleId);
        for (Integer permissionId : permissionIdList) {
            PlatformRolePermission rl = new PlatformRolePermission();
            rl.setPlatformRoleId(roleId);
            rl.setPlatformPermissionId(permissionId);
            rl.setCreateTime(new Date());
            platformRolePermissionDao.insert(rl);
        }

    }

}
